import React from 'react'
import {
  Card,
  Row,
  Col,
  Steps,
  Button,
  message,
  Empty,
  Spin,
  Modal,
} from 'antd'
import PageWrapper from 'components/PageWrapper'
import CarTree from 'components/CarTree'
import styles from '../G6Record/style.module.scss'
import Step0 from './Step0'
import Step1 from './Step1'
import Step2 from './Step2'
import Step3 from './Step3'
import axios from 'axios'
import { checkres } from 'utils'
import Log from './Log'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import balc from './img/balc.png'
import NingBOIndex from './NingBOIndex'
const { Step } = Steps

export default function G6Record() {
  const [selectId, setSelectId] = React.useState(null)
  const [current, setCurrent] = React.useState(0)
  const [data, setData] = React.useState({})
  const [loading, setLoading] = React.useState(false)
  const [isRead, setIsRead] = React.useState(false)
  const [code, setCode] = React.useState(null)
  const carTreeRef = React.useRef()
  const [ningBoFlag, setNingBoFlag] = React.useState(false)
  React.useEffect(() => {
    if (!selectId) return
    getDetail(selectId)
  }, [selectId])

  const getDetail = id => {
    setLoading(true)
    axios
      .get('/vehicleFiling/detailG5', { params: { vehicleId: id } })
      .then(res => {
        setLoading(false)
        if (!checkres(res)) return
        setData(res.data.data)
      })
  }

  const steps = [
    {
      title: '车辆静态备案（企业）',
      content: <Step0 record={data} />,
    },
    {
      title: '车辆销售区域备案（企业选填）',
      content: <Step1 record={data} />,
    },
    {
      title: '车辆二次备案（地方）',
      content: <Step2 record={data} />,
    },
    {
      title: '车辆通讯状态查询（地方）',
      content: <Step3 record={data} />,
    },
  ]

  const NingBO = {
    title: '车辆静态鉴权（企业）',
    content: <NingBOIndex record={data} />,
  }

  const selectTreeId = (selectId, text) => {
    console.log(text.areaAddr, '-----浙江省/宁波市 -------')
    setNingBoFlag(
      text.areaAddr.indexOf('宁波') > -1 || text.areaAddr.indexOf('杭州') > -1
        ? true
        : false
    )
    setSelectId(text.id)
    if (code) {
      if (code === text.areaId) {
        setIsRead(true)
      } else {
        setIsRead(false)
      }
    } else {
      setIsRead(false)
    }
    setCode(text.areaId)
  }

  const onChange = v => {
    if (!selectId) {
      message.error('请选择左侧车辆列表！')
      return false
    }
    setCurrent(v)
  }

  function next() {
    if (!selectId) {
      message.error('请选择左侧车辆列表！')
      return false
    }
    const newCurrent = current + 1
    setCurrent(newCurrent)
  }

  function prev() {
    if (!selectId) {
      message.error('请选择左侧车辆列表！')
      return false
    }
    const newCurrent = current - 1
    setCurrent(newCurrent)
  }

  function checkDisabled(current) {
    let flag = false
    switch (current) {
      case 0:
        {
          if (data.filingStatusG5 === 1) {
            flag = true
          }
        }
        break
      case 1:
        {
          if (data.areaFilingStatusG5 === 1) {
            flag = true
          }
        }
        break
      case 2:
        {
          if (data.twiceFilingStatusG5 * 1 === 1) {
            flag = true
          }
        }
        break
      case 3:
        {
          if (data.vehicleStatusG5 === 1) {
            flag = true
          }
        }
        break
    }
    return flag
  }

  function beian(current) {
    let url = ''
    const params = { vehicleId: data?.id }
    switch (current) {
      case 0:
        {
          url = '/vehicleFiling/insertVehicleEnterprise'
        }
        break
      case 1:
        {
          url = '/vehicleFiling/updateVehicleSaleArea'
        }
        break
      case 2:
        {
          url = '/vehicleFiling/updateVehicleLicense'
        }
        break
      case 3:
        {
          url = '/vehicleFiling/getVehicleDataReport'
        }
        break
      case 1024:
        {
          //---鉴权国五接口---修改此处URl判断提交宁波页面
          url = '/vehicleFilingNingBo/authenticationVehicleNingBo'
        }
        break
    }
    Modal.confirm({
      title: current === 3 ? '状态查询' : '申请备案',
      icon: <ExclamationCircleOutlined />,
      content: current === 3 ? '是否立即开始状态查询？' : '是否立即申请备案？',
      onOk() {
        return new Promise((resolve, reject) => {
          axios.get(url, { params: { ...params } }).then(res => {
            if (res.data.code === 1) {
              message.success(res.data.msg)
              getDetail(selectId)
              carTreeRef.current.update()
              resolve()
            } else {
              message.error(res.data.msg)
              reject()
            }
          })
        }).catch(() => console.log('Oops errors!'))
      },
      onCancel() {},
    })
  }

  function Page() {
    return (
      <div style={{ width: '100%', height: '100vh' }}>
        <img src={balc} style={{ width: '100%' }}></img>
        <div style={{ margin: '24px auto', width: 120 }}>
          <Button style={{ width: 120 }} onClick={() => setIsRead(true)}>
            知道啦
          </Button>
        </div>
      </div>
    )
  }

  function Node() {
    return ningBoFlag ? (
      <>
        <Steps>
          <Step key={NingBO.title} title={NingBO.title} />
        </Steps>
        <div className={styles.stepscontent}>{NingBO.content}</div>
        <Log record={data}></Log>
        <Button
          type="primary"
          disabled={checkDisabled(0)}
          onClick={() => {
            beian(1024)
          }}
        >
          鉴权
        </Button>
      </>
    ) : (
      <Spin spinning={loading}>
        <Steps current={current} onChange={onChange}>
          {steps.map(item => (
            <Step key={item.title} title={item.title} />
          ))}
        </Steps>
        <div className={styles.stepscontent}>{steps[current].content}</div>
        <Log current={current} record={data}></Log>
        <div className={styles.stepsaction}>
          <Button
            type="primary"
            disabled={checkDisabled(current)}
            onClick={() => {
              beian(current)
            }}
          >
            {current === steps.length - 1 ? '状态查询' : '备案'}
          </Button>
          {current < steps.length - 1 && (
            <Button onClick={() => next()}>下一步</Button>
          )}
          {current > 0 && (
            <Button style={{ marginLeft: 8 }} onClick={() => prev()}>
              返回
            </Button>
          )}
        </div>
      </Spin>
    )
  }

  return (
    <PageWrapper>
      <Row gutter={12}>
        <Col span={6}>
          <Card title="车辆列表" bordered={false} bodyStyle={{ paddingTop: 0 }}>
            <div
              className="vinTree"
              style={{ maxHeight: 500, overflowY: 'auto', overflowX: 'auto' }}
            >
              <CarTree
                ref={carTreeRef}
                selectTreeId={selectTreeId}
                selectType="name"
                isG5={true}
              />
            </div>
          </Card>
        </Col>
        <Col span={18}>
          <Card>
            {selectId ? (
              isRead ? (
                <Node></Node>
              ) : (
                <Page></Page>
              )
            ) : (
              <Empty style={{ height: 800 }} description="无选中车辆" />
            )}
          </Card>
        </Col>
      </Row>
    </PageWrapper>
  )
}
